<script setup>
import {
    Edit,
    Delete,
    Search,
    View,
    Close,
    Check,
    Plus,
    Refresh
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import { formatDate } from '@/utils/format.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVendorListService } from '@/api/vendor.js'
import { 
    getOrderListService, 
    addOrderService, 
    updateOrderService, 
    deleteOrderService, 
    getOrderDetailService,
    batchDeleteOrderService 
} from '@/api/order.js'

//订单数据模型
const orders = ref([])
//供应商数据模型
const vendors = ref([])
const vendorId = ref()

//回显供应商列表
const echoVendorList = async () => {
    let res = await getVendorListService()
    vendors.value = res.data
}
echoVendorList()
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getOrderList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    getOrderList()
}

// 下拉框 订单状态模型
const statusList = ref([
    {
        name: '待发货',
        id: 0
    },
    {
        name: '已发货',
        id: 1
    },
    {
        name: '待出库',
        id: 2
    },
    {
        name: '已出库',
        id: 3
    },
    {
        name: '已完成',
        id: 4
    }
])
const status = ref('')
const visibleDrawer = ref(false)
const orderModel = ref({
    id: '',
    vendorId: '',
    status: '',
    orderDetails: []
})
const formRef = ref(null)

const removeDomain = function (item) {
    const index = orderModel.domains.indexOf(item)
    if (index !== -1) {
        orderModel.domains.splice(index, 1)
    }
}

const addDomain = function () {
    orderModel.domains.push({
        key: Date.now(),
        value: '',
    })
}
const title = ref('')
const orderNumber = ref()
//查询供应商列表
const getOrderList = async () => {
    let res = await getOrderListService({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        orderNumber: orderNumber.value ? orderNumber.value : null
    })
    orders.value = res.data.items
    total.value = res.data.total
    // 循环处理订单状态
    for (let i = 0; i < orders.value.length; i++) {
        for (let j = 0; j < statusList.value.length; j++) {
            if (orders.value[i].status == statusList.value[j].id) {
                orders.value[i].statusName = statusList.value[j].name
            }
        }
    }
    //处理供应商名称
    for (let i = 0; i < orders.value.length; i++) {
        for (let j = 0; j < vendors.value.length; j++) {
            if (orders.value[i].vendorId == vendors.value[j].id) {
                orders.value[i].vendorName = vendors.value[j].vendorName
            }
        }
    }
}
getOrderList()

// 表格数据
const tableData = ref([
    {
        productName: '',
        quantity: '',
        price: ''
    }
])

// 添加行
const addRow = () => {
    tableData.value.push({
        productName: '',
        quantity: '',
        price: ''
    })
}

// 删除行
const removeRow = (index) => {
    if (tableData.value.length > 1) {
        tableData.value.splice(index, 1)
    } else {
        ElMessage.warning('至少保留一行数据')
    }
}

//添加订单
const addOrder = async () => {
    try {
        // 验证表单数据
        if (!vendorId.value) {
            ElMessage.warning('请选择供应商')
            return
        }
        if (status.value === '') {
            ElMessage.warning('请选择订单状态')
            return
        }
        // 验证订单明细
        for (const item of tableData.value) {
            if (!item.productName) {
                ElMessage.warning('请输入商品名称')
                return
            }
            if (!item.quantity) {
                ElMessage.warning('请输入商品数量')
                return
            }
            if (!item.price) {
                ElMessage.warning('请输入商品单价')
                return
            }
        }
        
        // 构建订单数据
        const orderData = {
            vendorId: vendorId.value,
            status: status.value,
            orderDetails: tableData.value.map(item => ({
                productName: item.productName,
                quantity: item.quantity,
                price: item.price
            }))
        }
        
        const res = await addOrderService(orderData)
        if (res.code === 0) {
            ElMessage.success(res.message || '添加成功')
    visibleDrawer.value = false
            await getOrderList() // 刷新列表
            clearOrder() // 清空表单
        } else {
            ElMessage.error(res.message || '添加失败')
        }
    } catch (error) {
        console.error('添加订单失败:', error)
        ElMessage.error('系统错误，请稍后重试')
    }
}

//清空表单
const clearOrder = () => {
    orderModel.value = {
        id: '',
        vendorId: '',
        status: '',
        orderDetails: []
    }
    vendorId.value = ''
    status.value = ''
    tableData.value = [{
        productName: '',
        quantity: '',
        price: ''
    }]
}
//回显供应商信息
const editOrder = async (row) => {
    try {
        const res = await getOrderDetailService(row.id)
        if (res.code === 0) {
            const orderDetail = res.data
            orderModel.value = {
                id: orderDetail.id,
                vendorId: orderDetail.vendorId,
                status: orderDetail.status,
                orderDetails: orderDetail.orderDetails || []
            }
            vendorId.value = orderDetail.vendorId
            status.value = orderDetail.status
            // 设置表格数据，确保使用正确的ID字段
            if (orderDetail.orderDetails) {
                tableData.value = orderDetail.orderDetails.map(item => ({
                    ...item,
                    orderItemId: item.id || item.orderItemId
                }))
            } else {
                tableData.value = [{
                    productName: '',
                    quantity: '',
                    price: ''
                }]
            }
    title.value = '编辑订单'
    visibleDrawer.value = true
        } else {
            ElMessage.error(res.message || '获取订单详情失败')
        }
    } catch (error) {
        console.error('编辑订单失败:', error)
        ElMessage.error('获取订单详情失败')
    }
}
//更新订单信息
const updateOrder = async () => {
    // 验证表单数据
    if (!vendorId.value) {
        ElMessage.warning('请选择供应商')
        return
    }
    if (status.value === '') {
        ElMessage.warning('请选择订单状态')
        return
    }
    // 验证订单明细
    for (const item of tableData.value) {
        if (!item.productName) {
            ElMessage.warning('请输入商品名称')
            return
        }
        if (!item.quantity) {
            ElMessage.warning('请输入商品数量')
            return
        }
        if (!item.price) {
            ElMessage.warning('请输入商品单价')
            return
        }
    }
    
    try {
        // 构建订单数据
        const orderData = {
            id: orderModel.value.id,
            vendorId: vendorId.value,
            status: status.value,
            orderDetails: tableData.value.map(item => ({
                orderItemId: item.orderItemId,
                productName: item.productName,
                quantity: item.quantity,
                price: item.price
            }))
        }
        let res = await updateOrderService(orderData)
        if (res.code === 0) {
            ElMessage.success(res.message || '更新成功')
    visibleDrawer.value = false
            await getOrderList() // 刷新列表
            clearOrder() // 清空表单
        } else {
            ElMessage.error(res.message || '更新失败')
        }
    } catch (error) {
        ElMessage.error('系统错误，请稍后重试')
    }
}
//删除订单
const deleteOrder = async (id) => {
    try {
        const result = await ElMessageBox.confirm(
            '确定要删除该订单吗？此操作不可恢复',
            '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            }
        )
        
        if (result) {
            const res = await deleteOrderService(id)
            if (res.code === 0) {
                ElMessage.success('删除成功')
                await getOrderList() // 刷新列表
            } else {
                ElMessage.error(res.message || '删除失败')
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('系统错误，请稍后重试')
        }
    }
}
// 订单详情
const visible = ref(false)
const orderInfo = ref({})
const viewOrder = async (row) => {
    try {
        const res = await getOrderDetailService(row.id)
        if (res.code === 0) {
            orderInfo.value = res.data
            // 处理订单状态名称
            for (let i = 0; i < statusList.value.length; i++) {
                if (orderInfo.value.status === statusList.value[i].id) {
                    orderInfo.value.statusName = statusList.value[i].name
                }
            }
            // 处理供应商名称
            for (let i = 0; i < vendors.value.length; i++) {
                if (orderInfo.value.vendorId === vendors.value[i].id) {
                    orderInfo.value.vendorName = vendors.value[i].vendorName
                }
            }
            // 确保订单明细使用正确的ID字段
            if (orderInfo.value.orderDetails) {
                orderInfo.value.orderDetails = orderInfo.value.orderDetails.map(item => ({
                    ...item,
                    orderItemId: item.id || item.orderItemId
                }))
            }
    visible.value = true
        } else {
            ElMessage.error(res.message || '获取订单详情失败')
        }
    } catch (error) {
        ElMessage.error('获取订单详情失败')
    }
}

// 批量删除商品
const ids = ref([])
const handleSelectionChange = (rows) => {
    ids.value = rows.map(v => v.id)
    console.log(ids.value);
}
const deleteOrdersById = async () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请选择要删除的订单')
        return
    }
    
    try {
        const result = await ElMessageBox.confirm(
            '确定要删除选中的订单吗？此操作不可恢复',
            '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            }
        )
        
        if (result) {
            const res = await batchDeleteOrderService(ids.value)
            if (res.code === 0) {
                ElMessage.success('批量删除成功')
                await getOrderList() // 刷新列表
                ids.value = [] // 清空选中
            } else {
                ElMessage.error(res.message || '批量删除失败')
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('系统错误，请稍后重试')
        }
    }
}


</script>
<template>
    <div class="page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span class="title">订单管理</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="title = '创建订单'; clearOrder(); visibleDrawer = true" class="add-button">
                            <el-icon><Plus /></el-icon>创建订单
                        </el-button>
                        <el-button type="danger" @click="deleteOrdersById" class="delete-button">
                            <el-icon><Delete /></el-icon>批量删除
                        </el-button>
                    </div>
    </div>
            </template>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item label="订单编号">
                        <el-input 
                            v-model="orderNumber" 
                            placeholder="请输入订单编号" 
                            clearable 
                            prefix-icon="Search"
                            class="custom-input"
                        />
            </el-form-item>
            <el-form-item>
                        <el-button type="primary" @click="getOrderList" class="search-button">
                            <el-icon><Search /></el-icon>搜索
                        </el-button>
                        <el-button @click="orderNumber = '', getOrderList" class="reset-button">
                            <el-icon><Refresh /></el-icon>重置
                        </el-button>
            </el-form-item>
        </el-form>
            </div>

            <!-- 订单列表 - 只显示订单表字段 -->
            <el-table 
                :data="orders" 
                style="width: 100%" 
                border 
                stripe
                @selection-change="handleSelectionChange"
                :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
                :row-style="{ height: '60px' }"
                :cell-style="{ padding: '8px 0' }"
                highlight-current-row>
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" width="80" type="index" align="center" />
                <el-table-column label="订单编号" min-width="150" prop="orderNumber" align="center" show-overflow-tooltip />
                <el-table-column label="下单人" min-width="120" prop="username" align="center" show-overflow-tooltip />
                <el-table-column label="供应商名称" min-width="120" prop="vendorName" align="center" show-overflow-tooltip />
                <el-table-column label="订单状态" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 0 ? 'warning' : 
                               row.status === 1 ? 'primary' : 
                               row.status === 2 ? 'info' : 
                               row.status === 3 ? 'success' : 'danger'">
                            {{ row.statusName }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="下单时间" min-width="180" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatDate(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" min-width="180" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatDate(row.updateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-tooltip content="查看" placement="top">
                                <el-button :icon="Search" circle type="primary" @click="viewOrder(row)" size="small" />
                            </el-tooltip>
                            <el-tooltip content="编辑" placement="top">
                                <el-button :icon="Edit" circle type="primary" @click="editOrder(row)" size="small" />
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button :icon="Delete" circle type="danger" @click="deleteOrder(row.id)" size="small" />
                            </el-tooltip>
                        </div>
                </template>
            </el-table-column>
            <template #empty>
                    <el-empty description="暂无订单数据" />
                </template>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="onSizeChange"
                    @current-change="onCurrentChange"
                />
            </div>
        </el-card>

        <!-- 详情弹框 - 显示订单详情 -->
        <el-dialog 
            v-model="visible" 
            width="60%" 
            destroy-on-close
            class="custom-dialog"
            :show-close="false">
            <template #header>
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon class="title-icon"><View /></el-icon>
                        <span>订单详情</span>
                    </div>
                    <el-button class="close-button" @click="visible = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="dialog-content-wrapper">
                <div class="dialog-content">
                    <div class="order-header">
                        <div class="order-title">
                            <h2>订单信息</h2>
                            <el-tag :type="orderInfo.status === 0 ? 'warning' : 
                                   orderInfo.status === 1 ? 'primary' : 
                                   orderInfo.status === 2 ? 'info' : 
                                   orderInfo.status === 3 ? 'success' : 'danger'">
                                {{ orderInfo.statusName }}
                            </el-tag>
                        </div>
                        <div class="order-number">
                            <span>订单编号：</span>
                            <span class="highlight">{{ orderInfo.orderNumber }}</span>
                        </div>
                    </div>
                    
                    <el-divider />
                    
                    <div class="order-content">
                        <div class="info-section">
                            <h3>基本信息</h3>
                            <el-descriptions :column="2" border>
                                <el-descriptions-item label="供应商名称">{{ orderInfo.vendorName }}</el-descriptions-item>
                                <el-descriptions-item label="下单人">{{ orderInfo.username }}</el-descriptions-item>
                                <el-descriptions-item label="下单时间">{{ formatDate(orderInfo.createTime) }}</el-descriptions-item>
                                <el-descriptions-item label="更新时间">{{ formatDate(orderInfo.updateTime) }}</el-descriptions-item>
                            </el-descriptions>
                        </div>
                        
                        <div class="info-section">
                            <h3>订单明细</h3>
                            <el-table :data="orderInfo.orderDetails || []" style="width: 100%" border>
                                <el-table-column label="商品名称" prop="productName" align="center" />
                                <el-table-column label="数量" prop="quantity" width="120" align="center" />
                                <el-table-column label="单价/元" prop="price" width="120" align="center" />
                                <el-table-column label="总价/元" width="120" align="center">
                                    <template #default="scope">
                                        {{ (scope.row.quantity * scope.row.price).toFixed(2) }}
                                    </template>
                                </el-table-column>
        </el-table>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="visible = false" class="close-dialog-button">
                        <el-icon><Close /></el-icon>关闭
                    </el-button>
                </div>
            </template>
    </el-dialog>

        <!-- 抽屉 - 创建/编辑订单表单 -->
        <el-drawer 
            v-model="visibleDrawer" 
            :title="title" 
            direction="rtl" 
            size="60%"
            :before-close="clearOrder"
            destroy-on-close
            :show-close="false"
            class="custom-drawer">
            <template #header>
                <div class="drawer-header">
                    <div class="drawer-title">
                        <el-icon class="title-icon"><component :is="title === '创建订单' ? Plus : Edit" /></el-icon>
                        <span>{{ title }}</span>
                    </div>
                    <el-button class="close-button" @click="visibleDrawer = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="drawer-content">
                <el-form :model="orderModel" label-width="100px" class="drawer-form">
                    <div class="form-section">
                        <h3>基本信息</h3>
                        <el-form-item label="供应商" required>
                            <el-select 
                                v-model="vendorId" 
                                placeholder="请选择供应商" 
                                class="custom-input">
                                <el-option 
                                    v-for="c in vendors" 
                                    :key="c.id" 
                                    :label="c.vendorName" 
                                    :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
                        <el-form-item label="订单状态" required>
                            <el-select 
                                v-model="status" 
                                placeholder="请选择订单状态" 
                                class="custom-input">
                                <el-option 
                                    v-for="c in statusList" 
                                    :key="c.id" 
                                    :label="c.name" 
                                    :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
                    </div>

                    <el-divider />

                    <div class="form-section">
                        <div class="section-header">
                            <h3>订单明细</h3>
                            <el-button type="primary" @click="addRow" class="add-row-button">
                                <el-icon><Plus /></el-icon>添加商品
                    </el-button>
                        </div>
                        <el-table 
                            :data="tableData" 
                            style="width: 100%" 
                            border
                            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }">
                            <el-table-column label="商品名称" min-width="200">
                                <template #default="scope">
                                    <el-input 
                                        v-model="scope.row.productName" 
                                        placeholder="请输入商品名称"
                                        class="custom-input" 
                                    />
                        </template>
                    </el-table-column>
                            <el-table-column label="数量" width="150">
                                <template #default="scope">
                                    <el-input-number 
                                        v-model="scope.row.quantity" 
                                        :min="1" 
                                        placeholder="请输入数量" 
                                        class="custom-input" 
                                    />
                        </template>
                    </el-table-column>
                            <el-table-column label="单价/元" width="150">
                                <template #default="scope">
                                    <el-input-number 
                                        v-model="scope.row.price" 
                                        :min="0" 
                                        :precision="2" 
                                        placeholder="请输入单价" 
                                        class="custom-input" 
                                    />
                        </template>
                    </el-table-column>
                            <el-table-column label="操作" width="100" fixed="right" align="center">
                                <template #default="scope">
                                    <el-button type="danger" @click="removeRow(scope.$index)" class="delete-button" link>
                                        删除
                                    </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                    </div>

                    <el-form-item class="drawer-footer">
                        <el-button type="primary" @click="title === '创建订单' ? addOrder() : updateOrder()" class="submit-button">
                            <el-icon><Check /></el-icon>{{ title === '创建订单' ? '创建' : '更新' }}
                        </el-button>
                        <el-button @click="visibleDrawer = false" class="cancel-button">
                            <el-icon><Close /></el-icon>取消
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
    </el-drawer>
    </div>
</template>
<style lang="scss" scoped>
.page-container {
    padding: 20px;
    
    .box-card {
        margin-bottom: 20px;
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title {
            font-size: 16px;
            font-weight: bold;
        }
        
        .header-actions {
            display: flex;
            gap: 10px;
        }
    }
    
    .search-area {
        margin-bottom: 20px;
    }
}

.add-row-button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
    display: inline-flex !important;
    align-items: center;
    gap: 5px;
    background-color: var(--el-color-primary) !important;
    border-color: var(--el-color-primary) !important;
    color: white !important;
    cursor: pointer;
    
    &:hover {
        background-color: var(--el-color-primary-light-3) !important;
        border-color: var(--el-color-primary-light-3) !important;
    }
    
    .el-icon {
        margin-right: 4px;
        font-size: 16px;
    }
}

.section-header {
            display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h3 {
        margin: 0;
        font-size: 16px;
        color: #303133;
    }
}

.drawer-content {
    padding: 20px;
    height: calc(100% - 120px);
    overflow-y: auto;
    
    .form-section {
        margin-bottom: 30px;
        
        h3 {
            margin-bottom: 20px;
            font-size: 16px;
            color: #303133;
        }
    }
    
    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }
    
    .custom-input {
        width: 100%;
    }
}

.drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 20px;
    text-align: right;
    background-color: white;
    border-top: 1px solid #e4e7ed;
    z-index: 1;
}

:deep(.el-descriptions) {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

:deep(.el-table) {
            margin-top: 10px;
}

:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-drawer__body) {
    padding: 0;
    position: relative;
    overflow: hidden;
}

.operation-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
    
    .dialog-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: bold;
        
        .title-icon {
            font-size: 20px;
            color: var(--el-color-primary);
        }
    }
}

.dialog-content {
    padding: 20px;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .order-title {
        display: flex;
        align-items: center;
        gap: 15px;
        
        h2 {
            margin: 0;
            font-size: 20px;
            color: #303133;
        }
    }
    
    .order-number {
        font-size: 16px;
        color: #606266;
        
        .highlight {
            color: var(--el-color-primary);
            font-weight: bold;
        }
    }
}

.info-section {
    margin-bottom: 30px;
    
    h3 {
        margin: 0 0 15px 0;
        font-size: 16px;
        color: #303133;
    }
}
</style>